package Servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.Student;
import service.Impl.StudentServiceImpl;
import service.StudentService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out =resp.getWriter();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        StudentService studentService=new StudentServiceImpl();
        List<Student> listAll=studentService.getAll();
        String jsonStr= JSON.toJSONString(listAll);
        System.out.println(jsonStr);
        out.print(jsonStr);

        String opr=req.getParameter("opr");
        if ("add".equals(opr)){
            String name=req.getParameter("name");
            String  address=req.getParameter("address");
            String sex=req.getParameter("sex");
            int addHangshu=studentService.add(name,address,sex);
            ServletContext application=this.getServletContext();
            if (addHangshu>0){
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
                out.print("<script>alert('新增成功')</script>");
            }
        }

        else if ("update".equals(opr)){
            int id=Integer.parseInt(req.getParameter("updateid"));
            String name=req.getParameter("updatename");
            String  address=req.getParameter("updateaddress");
            String sex=req.getParameter("updatesex");
            int updateHangshu=studentService.update(id,name,address,sex);
            ServletContext application=this.getServletContext();
            if (updateHangshu>0){
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
                out.print("<script>alert('修改成功')</script>");
            }
        }

        else if ("delete".equals(opr)){
            int id=Integer.parseInt(req.getParameter("deleteid"));
            int deleteHangshu=studentService.delete(id);
            ServletContext application=this.getServletContext();
            if (deleteHangshu>0){
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
                out.print("<script>alert('删除成功')</script>");
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
